import { NextRequest, NextResponse } from 'next/server';
import { mockUsers } from '@/mock/users';
import { AuthUser, ApiResponse } from '@/types/auth';
import { validateToken, parseTokenUser } from '@/utils/auth';

// GET /api/auth/me - 获取当前用户信息
export async function GET(request: NextRequest) {
  try {
    // 从请求头获取 token
    const authorization = request.headers.get('authorization');
    if (!authorization || !authorization.startsWith('Bearer ')) {
      return NextResponse.json(
        { success: false, message: '未提供有效的认证信息' },
        { status: 401 }
      );
    }

    const token = authorization.slice(7); // 移除 'Bearer ' 前缀

    // 验证 token
    if (!validateToken(token)) {
      return NextResponse.json(
        { success: false, message: 'Token 无效或已过期' },
        { status: 401 }
      );
    }

    // 从 token 解析用户信息
    const tokenUser = parseTokenUser(token);
    if (!tokenUser || !tokenUser.id) {
      return NextResponse.json(
        { success: false, message: '无法解析用户信息' },
        { status: 401 }
      );
    }

    // 查找完整的用户信息
    const user = mockUsers.find(u => u.id === tokenUser.id);
    if (!user) {
      return NextResponse.json(
        { success: false, message: '用户不存在' },
        { status: 404 }
      );
    }

    // 检查用户状态
    if (user.status !== 'active') {
      return NextResponse.json(
        { success: false, message: '用户账户已被禁用' },
        { status: 403 }
      );
    }

    // 角色权限映射（与登录 API 保持一致）
    const rolePermissions: Record<string, string[]> = {
      admin: [
        'user:read', 'user:create', 'user:update', 'user:delete',
        'ticket:read', 'ticket:create', 'ticket:update', 'ticket:delete',
        'system:read', 'system:update'
      ],
      manager: [
        'user:read', 'user:update',
        'ticket:read', 'ticket:create', 'ticket:update', 'ticket:delete'
      ],
      user: [
        'ticket:read', 'ticket:create', 'ticket:update'
      ],
      guest: [
        'ticket:read'
      ]
    };

    // 构建认证用户信息
    const authUser: AuthUser = {
      id: user.id,
      username: user.username,
      email: user.email,
      displayName: user.displayName,
      avatar: user.avatar,
      role: user.role as any,
      permissions: rolePermissions[user.role] || [],
    };

    const response: ApiResponse<AuthUser> = {
      success: true,
      data: authUser,
    };

    return NextResponse.json(response);
  } catch (error) {
    console.error('获取用户信息失败:', error);
    return NextResponse.json(
      { success: false, message: '获取用户信息失败' },
      { status: 500 }
    );
  }
} 